package com.bluedot.dao;

import com.bluedot.dao.pool.BluedotConnectionPoolManage;
import com.bluedot.pojo.pack.PreMappedStatement;

import java.sql.Connection;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 数据层队列
 *
 * @author chenzou'quan
 */
public class DataQueue {
    private static Queue<PreMappedStatement> dataQueue = new ConcurrentLinkedQueue<>();
    private static Queue returnQueue = new ConcurrentLinkedQueue();

    protected PreMappedStatement data = null;

    protected Object result = null;

    /**
     * 数据库连接池管理类
     */
    protected static BluedotConnectionPoolManage poolManage = new BluedotConnectionPoolManage();

    /**
     * 普通队列
     * @param preMappedStatement
     * @return
     */
    protected Object add(PreMappedStatement preMappedStatement) {
        dataQueue.add(preMappedStatement);
        new SQL().update();
        Object remove = returnQueue.remove();
        return remove;
    }

    /**
     * 单个缓冲物
     * @param preMappedStatement
     * @return
     */
    protected Object addData(PreMappedStatement preMappedStatement) {
        // 1. 判断数据库连接池是否初始化成功
        if (poolManage == null){
            throw new RuntimeException("连接池初始化失败!");
        }
        // 2. 获取数据库连接
        Connection connection = BluedotConnectionPoolManage.getConnection();
        // 3. 数据库操作
        SQL sql = new SQL(connection);
        sql.data = preMappedStatement;
        sql.updateData();
        // 4. 释放数据库连接
        BluedotConnectionPoolManage.releaseConnection(connection);
        return sql.result;
    }

    protected Object addBackups(PreMappedStatement preMappedStatement, Connection connection) {
        dataQueue.add(preMappedStatement);
        new SQL(connection).update();
        Object remove = returnQueue.remove();
        return remove;
    }

    public static Queue<PreMappedStatement> getDataQueue() {
        return dataQueue;
    }

    public static Queue getReturnQueue() {
        return returnQueue;
    }
}
